import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router/index'
import URL from '@/config/url'
import conf from '@/config'
import { throttle } from '@/utils'
import { getToken } from '@/utils/token'

const throttleMessage = throttle(message => Message.error(message || '登录超时,请重新登录'), conf.timeout)

/**
 * 创建基础服务
 * @param { Object } options axios的基本配置
 */
const createService = options => {
  const service = axios.create({ timeout: conf.timeout, ...options })

  service.interceptors.request.use(
    // 先进后出
    config => {
      return config
    },
    error => {
      return Promise.reject(error)
    }
  )

  service.interceptors.response.use(
    // 先进先出
    response => {
      let res = response.data
      let { code, msg } = res
      if (code && code !== 0) {
        msg && Message.error(msg)
      }
      return res
    },
    error => {
      let { response = {} } = error
      if (error && response.status) {
        Message.error(response.data && response.data.msg ? response.data.msg : `服务器出现错误,请稍后重试! ${error}`)
      } else {
        Message.error('网络出现问题，请重新再试')
      }
      return Promise.reject(error)
    }
  )

  return service
}

/**
 * 处理带Token获取数据的请求和相应拦截
 * @param { Object } options axios的基本配置
 */
const createHasTokenService = options => {
  const service = createService(options)

  service.interceptors.request.use(config => {
    let token = getToken()
    if (!token) {
      store.dispatch('HANDLE_LOGOUT')
      router.replace('/login')
      return
    }
    store.dispatch('SET_LOADING', true)
    config.headers[conf.token] = token
    return config
  })

  service.interceptors.response.use(
    response => {
      store.dispatch('SET_LOADING', false)
      let { code, msg } = response
      if (code && [10000, 10001, 10002].includes(code)) {
        store.dispatch('HANDLE_LOGOUT')
        router.replace('/login')
        return throttleMessage(msg)
      }
      return response
    },
    error => {
      let { status, data } = error.response
      if (status === 401) {
        let { code, msg } = data
        if ([10000, 10001, 10002].includes(code)) {
          store.dispatch('HANDLE_LOGOUT')
          router.replace('/login')
          return throttleMessage(msg)
        }
      }
      store.dispatch('SET_LOADING', false)
      return Promise.reject(error)
    }
  )

  return service
}

export const request = createService({ baseURL: URL.baseURL })
export const requestHasToken = createHasTokenService({ baseURL: URL.baseURL })
